<?php

class viewProfileDocumentTypesAction extends sfAction
{

    private $profileDocumentTypeConfigurationService;

    public function getProfileDocumentTypeConfigurationService()
    {

        if (!($this->profileDocumentTypeConfigurationService instanceof ProfileDocumentTypeConfigurationService)) {
            $this->profileDocumentTypeConfigurationService = new ProfileDocumentTypeConfigurationService();
        }

        return $this->profileDocumentTypeConfigurationService;
    }

    public function setProfileDocumentTypeConfigurationService($profileDocumentTypeConfigurationService)
    {
        $this->profileDocumentTypeConfigurationService = $profileDocumentTypeConfigurationService;
    }

    public function execute($request)
    {

        $this->_checkAuthentication();

        $this->form = new ProfileDocumentTypeForm();
        $profileDocumentTypeConfigurationService = $this->getProfileDocumentTypeConfigurationService();
        $this->sorter = new ListSorter('property.sort', 'tlupim_module', $this->getUser(), array('field_num', ListSorter::ASCENDING));

        $sortBy = 'code';
        $sortOrder = 'ASC';

        if ($request->getParameter('sort')) {
            $sortBy = $request->getParameter('sort');
            $sortOrder = $request->getParameter('order');
            $this->sortField = $sortBy;
            $this->sortOrder = $sortOrder;
        }
        $this->sorter->setSort(array($sortBy, $sortOrder));
        $this->records = $profileDocumentTypeConfigurationService->getProfileDocumentTypeList($sortBy, $sortOrder, true);

        if ($request->isMethod('post')) {

            $this->form->bind($request->getParameter($this->form->getName()));

            if ($this->form->isValid()) {

                $this->_checkDuplicateEntry();

                $templateMessage = $this->form->save();
                $this->getUser()->setFlash($templateMessage['messageType'], $templateMessage['message']);
                $this->redirect('tlupim/viewProfileDocumentTypes');

            }

        }

    }

    protected function _checkAuthentication()
    {

        $user = $this->getUser()->getAttribute('user');

        if (!$user->isAdmin()) {
            $this->redirect('pim/viewPersonalDetails');
        }

    }

    protected function _checkDuplicateEntry()
    {

        $id = $this->form->getValue('id');
        $object = $this->getProfileDocumentTypeConfigurationService()->getProfileDocumentTypeByCode($this->form->getValue('code'));

        if ($object instanceof ProfileDocumentType) {

            if (!empty($id) && $id == $object->getId()) {
                return false;
            }

            $this->getUser()->setFlash('warning', __('Code Already Exists'));
            $this->redirect('tlupim/viewProfileDocumentTypes');

        }

        return false;

    }

}
